﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Control.Bus;

namespace QuanLyKho
{
    public partial class Form1 : Form
    {
        List<BusImportBillDetail> BillDetails = new List<BusImportBillDetail>();
        List<BusImportBillDetail> BillDetailstoDelete = new List<BusImportBillDetail>();
        BusImportBillDetail BillDetailtoUpdate = null;
        bool saved = true;
        BusStaff staff = new BusStaff()
        {
            ID = 1,
            UserName = "admin",
            PassWord = "admin"
        };
        BusImportBill Bill = new BusImportBill();
        public Form1()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            //dataGridView1.DataSource = BillDetails;
            Bill = BusImportBill.FindByDateAndStaff(DateTime.Now, staff);
            if (Bill.ID == -1)
            {
                Bill.Staff = staff;
                Bill.Date = DateTime.Now;
                Bill.Insert();
            }
        }
        public Form1(BusImportBill _Bill, BusStaff _Staff)
        {
            InitializeComponent();
            staff = _Staff;
            Bill = _Bill;
            if (Bill.ID == -1)
            {
                Bill.Insert();
            }
            BillDetails = Bill.GetListBillDetails();
            dataGridView1.AutoGenerateColumns = false;
            if (BillDetails.Count != 0)
                bindingDataSource();
        }
        private void txtMa_TextChanged(object sender, EventArgs e)
        {
            string MaProd = txtMa.Text;
            BusProduct Prod = BusProduct.GetProdByCode(MaProd);
            try
            {
                lbTenValue.Text = Prod.ProductName;
                lbTonValue.Text = Prod.GetTonKho().ToString();
                lbKeValue.Text = Prod.ShelfName;
            }
            catch
            {
                lbTenValue.Text = "no value";
                lbKeValue.Text = "no value";
                lbTonValue.Text = "no value";
            }

        }

        private void btThoat_Click(object sender, EventArgs e)
        {
            if (saved==true)
            {
                this.Close();
            }
            else
            {
                DialogResult dialogresuilt = MessageBox.Show("Một só dữ liệu chưa được lưu. Bạn có muôn lưu không ?", "Xac Dinh", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dialogresuilt == DialogResult.Yes)
                {
                    Luu();
                    this.Close();
                }
                else if (dialogresuilt == DialogResult.No)
                            this.Close();
                
            }
            
        }

        private void btNhap_Click(object sender, EventArgs e)
        {
            nhapdatagrid();
            clear();
            IsNotSave();
        }

        private void clear()
        {
            txtMa.Text = null;
            txtSoLuong.Text = null;
            lbKeValue.Text = "no value";
            lbTonValue.Text = "no value";
            lbTenValue.Text = "no value";
            BillDetailtoUpdate = null;
          

        }

        private void nhapdatagrid()
        {
            string MaProd = txtMa.Text;
            BusProduct Prod = BusProduct.GetProdByCode(MaProd);
                BusImportBillDetail billdetail = new BusImportBillDetail()
                {
                    ID = -1,
                    Bill = Bill,
                    Prod = Prod,
                    Quantity = int.Parse(txtSoLuong.Text)
                };
                BillDetails.Add(billdetail);
            if(BillDetailtoUpdate!=null)
            {
                BillDetails.Remove(BillDetailtoUpdate);
                BillDetailstoDelete.Add(BillDetailtoUpdate);
                
            }
            bindingDataSource();
          
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                row.Selected = false;
            }
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
        }

        private void bindingDataSource()
        {
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = BillDetails;
        }

        private void btLuu_Click(object sender, EventArgs e)
        {
            Luu();
        }

        private void Luu()
        {
            int i = 0;
            foreach (BusImportBillDetail item in BillDetails)
            {
                if (item.ID == -1 && item.Prod.ID != 0)
                    try
                    {

                        item.Insert();
                        item.IsSaved = true;
                    }
                    catch (Exception ex) { MessageBox.Show(ex.ToString()); }
                else
                {
                    item.UpDate();
                    item.IsSaved = true;
                }
                i++;
            }
            
            //for (int i = 0; i < BillDetails.Count; i++)
            //{
            //    if(BillDetails[i].ID==-1)
            //            try
            //            {
            //                MessageBox.Show("save " + BillDetails[i].Prod.ID);
            //                BillDetails[i].Insert();
            //                dataGridView1.Rows[i].Cells[3].Value = true;
            //            }
            //            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            //}
            foreach (BusImportBillDetail item in BillDetailstoDelete)
            {
                try
                {
                    item.Delete();
                }
                catch
                {

                }
            }
            BillDetailstoDelete = new List<BusImportBillDetail>();
            
            IsSaved();
        }

        private void IsSaved()
        {
            saved = true;
            groupBox3.Text = "Danh sách nhập";
        }

        private void btchonSp_Click(object sender, EventArgs e)
        {
            string ProdCode = null;
            FrmChooseProd frm = new FrmChooseProd();
            frm.ShowDialog();
            ProdCode = frm.Resuilt;
            txtMa.Text = ProdCode;
        }

        private void btXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("bạn có muốn xóa không ?", "Xac Dinh", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                List<BusImportBillDetail> delete = new List<BusImportBillDetail>();
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    delete.Add(BillDetails[row.Index]);
                }
                foreach (BusImportBillDetail item in delete)
                {
                    BillDetails.Remove(item);
                    if (item.ID > 0)
                    {
                        BusImportBillDetail Busremove = BusImportBillDetail.GetByID(item.ID);
                        BillDetailstoDelete.Add(Busremove);

                    }
                    else
                        BillDetailstoDelete.Add(item);
                }
                bindingDataSource();
                IsNotSave();
            }
        }

        private void IsNotSave()
        {
            saved = false;
            groupBox3.Text = "Danh sách nhập (*)";
        }

        private void btSua_Click(object sender, EventArgs e)
        {
            BusImportBillDetail billdetail = BillDetails[dataGridView1.SelectedRows[0].Index];
            txtMa.Text = billdetail.MaProd;
            txtSoLuong.Text = billdetail.Quantity.ToString();
            BillDetailtoUpdate = billdetail;
            //DataGridViewRow row = dataGridView1.SelectedRows[0];
            //txtMa.Text = row.Cells[1].Value.ToString();
            //txtSoLuong.Text = row.Cells[2].Value.ToString();
            //EditrowIndex = row.Index;

        }

        private void btHuy_Click(object sender, EventArgs e)
        {
            clear();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            

        }

 

        private void btPaste_Click(object sender, EventArgs e)
        {
            string s = Clipboard.GetText();
            string[] lines = s.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            //ITERATION HEADER-CHECK


            foreach (string line in lines)
            {
                string[] cells = line.Split('\t');
                BusProduct p = new BusProduct();
                p.ProductCode = cells[0];
                p.GetProperty();
                    int celllast = 0;
                    if (cells.Count() != 1)
                    {

                        try{celllast = int.Parse(cells.Last());}
                        catch{}
                    }


                    BusImportBillDetail bd = new BusImportBillDetail()
                    {
                        Bill = Bill,
                        Prod = p,
                        ID = -1,
                        Quantity = celllast,

                    };
                    BillDetails.Add(bd);
               
            }
            bindingDataSource();
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                row.Selected = false;
            }
            for (int i = dataGridView1.Rows.Count - lines.Count() ; i < dataGridView1.Rows.Count ; i++)
            {
                dataGridView1.Rows[i].Selected = true;
            }
            IsNotSave();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Control && e.KeyCode == Keys.V)
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lines)
                {
                    string[] cells = line.Split('\t');
                    BusProduct p = new BusProduct();
                    p.ProductCode = cells[0];
                    p.GetProperty();
                    int celllast = 0;
                    if (cells.Count() != 1)
                    {

                        try { celllast = int.Parse(cells.Last()); }
                        catch { }
                    }


                    BusImportBillDetail bd = new BusImportBillDetail()
                    {
                        Bill = Bill,
                        Prod = p,
                        ID = -1,
                        Quantity = celllast,

                    };
                    BillDetails.Add(bd);
                   
                }
                bindingDataSource();
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    row.Selected = false;
                }
                for (int i = dataGridView1.Rows.Count - lines.Count(); i < dataGridView1.Rows.Count; i++)
                {
                    dataGridView1.Rows[i].Selected = true;
                }
                IsNotSave();
            }
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                IsNotSave();
                BillDetails[e.RowIndex].IsSaved = false;
            }
        }


    }
}
